package com.gzu.project_manage.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String username = req.getHeader("username");
        String path = req.getRequestURI();
        if (!path.equals("/user/login") && !path.equals("/user/register")) {
            if (username == null) {
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                resp.getWriter().write("Request header lacks authentication field or authentication failed.");
            } else {
                req.setAttribute("username", username);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
